import React, {
  createContext,
  useState,
  useEffect,
  useContext,
  ReactNode,
} from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AuthState, AuthContextType, LoginCredentials } from './types';
import { User } from '../../types';
import { userService } from '../../services';
import { setShowLoginModalCallback, resetLoginModalState } from '../../services/httpClient';
import { AppConfig} from '../../config';
const AuthContext = createContext<AuthContextType | undefined>(undefined);

const AUTH_STORAGE_KEY = AppConfig.AUTH.TOKEN_KEY;

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [state, setState] = useState<AuthState>({
    user: null,
    token: null,
    isLoading: false,
    error: null,
  });
  const [showLoginModal, setShowLoginModal] = useState(false);

  // 初始化时从本地存储加载用户信息
  useEffect(() => {
    const loadStoredAuth = async () => {
      try {
        const storedAuth = await AsyncStorage.getItem(AUTH_STORAGE_KEY);
        if (storedAuth) {
          const { user, token } = JSON.parse(storedAuth);
          setState(prev => ({
            ...prev,
            user,
            token,
            isLoading: false,
          }));
        }
      } catch (error) {
        console.error('Failed to load stored auth', error);
      }
    };

    loadStoredAuth();
    
    // 设置全局登录模态框显示回调
    setShowLoginModalCallback(() => {
      setShowLoginModal(true);
    });
  }, []);

  // 保存认证信息到本地存储
  const saveAuthToStorage = async (user: User | null, token: string | null) => {
    try {
      if (user && token) {
        await AsyncStorage.setItem(
          AUTH_STORAGE_KEY,
          JSON.stringify({ user, token }),
        );
      } else {
        await AsyncStorage.removeItem(AUTH_STORAGE_KEY);
      }
    } catch (error) {
      console.error('Failed to save auth to storage', error);
    }
  };

  const login = async (credentials: LoginCredentials) => {
    setState(prev => ({ ...prev, isLoading: true, error: null }));

    try {
      // 调用真实API
      const { user, token } = await userService.login(credentials);

      setState({
        user,
        token,
        isLoading: false,
        error: null,
      });

      saveAuthToStorage(user, token);
      setShowLoginModal(false);
      resetLoginModalState();
    } catch (error: any) {
      const errorMessage = error?.message || 'Login failed';
      setState(prev => ({
        ...prev,
        isLoading: false,
        error: errorMessage,
      }));
      throw error;
    }
  };

  const logout = async () => {
    try {
      // 调用登出API
      await userService.logout();
    } catch (error) {
      console.error('Logout API call failed', error);
    } finally {
      setState({
        user: null,
        token: null,
        isLoading: false,
        error: null,
      });

      saveAuthToStorage(null, null);
    }
  };

  const updateUser = async (userData: Partial<User>) => {
    if (!state.user || !state.token) return;

    try {
      const updatedUser = await userService.updateProfile(userData);
      
      setState(prev => ({
        ...prev,
        user: updatedUser,
      }));

      // 更新本地存储
      if (state.token) {
        saveAuthToStorage(updatedUser, state.token);
      }
    } catch (error) {
      console.error('Failed to update user profile', error);
      throw error;
    }
  };

  const value = {
    ...state,
    login,
    logout,
    updateUser,
    showLoginModal,
    setShowLoginModal: (visible: boolean) => {
      setShowLoginModal(visible);
      if (!visible) {
        resetLoginModalState();
      }
    }
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};